/**
 * 亲戚关系计算引擎
 */
const RelationEngine = (function() {
    // 亲戚关系数据
    const relations = {
        // 基本关系定义
        me: { text: '我', gender: 'neutral' },
        father: { text: '爸爸', gender: 'male', reverse: 'son,daughter', template: '{{target}}的爸爸' },
        mother: { text: '妈妈', gender: 'female', reverse: 'son,daughter', template: '{{target}}的妈妈' },
        husband: { text: '丈夫', gender: 'male', reverse: 'wife', template: '{{target}}的丈夫' },
        wife: { text: '妻子', gender: 'female', reverse: 'husband', template: '{{target}}的妻子' },
        son: { text: '儿子', gender: 'male', reverse: 'father,mother', template: '{{target}}的儿子' },
        daughter: { text: '女儿', gender: 'female', reverse: 'father,mother', template: '{{target}}的女儿' },
        elder_brother: { text: '哥哥', gender: 'male', reverse: 'younger_brother,younger_sister', template: '{{target}}的哥哥' },
        younger_brother: { text: '弟弟', gender: 'male', reverse: 'elder_brother,elder_sister', template: '{{target}}的弟弟' },
        elder_sister: { text: '姐姐', gender: 'female', reverse: 'younger_brother,younger_sister', template: '{{target}}的姐姐' },
        younger_sister: { text: '妹妹', gender: 'female', reverse: 'elder_brother,elder_sister', template: '{{target}}的妹妹' }
    };

    // 复杂关系映射
    const complexRelations = {
        // 父系关系
        'father,father': { text: '爷爷', call: '爷爷' },
        'father,mother': { text: '奶奶', call: '奶奶' },
        'father,elder_brother': { text: '伯父', call: '伯父/伯伯' },
        'father,younger_brother': { text: '叔父', call: '叔叔' },
        'father,elder_sister': { text: '姑姑', call: '姑姑' },
        'father,younger_sister': { text: '姑姑', call: '姑姑' },
        
        // 母系关系
        'mother,father': { text: '外公', call: '外公' },
        'mother,mother': { text: '外婆', call: '外婆' },
        'mother,elder_brother': { text: '舅舅', call: '舅舅' },
        'mother,younger_brother': { text: '舅舅', call: '舅舅' },
        'mother,elder_sister': { text: '姨妈', call: '姨妈/姨姨' },
        'mother,younger_sister': { text: '姨妈', call: '姨妈/姨姨' },
        
        // 儿媳/女婿
        'son,wife': { text: '儿媳', call: '儿媳' },
        'daughter,husband': { text: '女婿', call: '女婿' },
        
        // 孙辈关系
        'son,son': { text: '孙子', call: '孙子' },
        'son,daughter': { text: '孙女', call: '孙女' },
        'daughter,son': { text: '外孙', call: '外孙' },
        'daughter,daughter': { text: '外孙女', call: '外孙女' },
        
        // 伯叔姑舅姨的子女
        'father,elder_brother,son': { text: '堂兄弟', call: '堂哥/堂弟' },
        'father,elder_brother,daughter': { text: '堂姐妹', call: '堂姐/堂妹' },
        'father,younger_brother,son': { text: '堂兄弟', call: '堂哥/堂弟' },
        'father,younger_brother,daughter': { text: '堂姐妹', call: '堂姐/堂妹' },
        'father,elder_sister,son': { text: '表兄弟', call: '表哥/表弟' },
        'father,elder_sister,daughter': { text: '表姐妹', call: '表姐/表妹' },
        'father,younger_sister,son': { text: '表兄弟', call: '表哥/表弟' },
        'father,younger_sister,daughter': { text: '表姐妹', call: '表姐/表妹' },
        'mother,elder_brother,son': { text: '表兄弟', call: '表哥/表弟' },
        'mother,elder_brother,daughter': { text: '表姐妹', call: '表姐/表妹' },
        'mother,younger_brother,son': { text: '表兄弟', call: '表哥/表弟' },
        'mother,younger_brother,daughter': { text: '表姐妹', call: '表姐/表妹' },
        'mother,elder_sister,son': { text: '表兄弟', call: '表哥/表弟' },
        'mother,elder_sister,daughter': { text: '表姐妹', call: '表姐/表妹' },
        'mother,younger_sister,son': { text: '表兄弟', call: '表哥/表弟' },
        'mother,younger_sister,daughter': { text: '表姐妹', call: '表姐/表妹' }
    };

    // 关系简化规则
    const simplificationRules = [
        // 特殊情况：自己
        {
            pattern: ['father', 'son'],
            condition: (path, index) => index+1 < path.length && !path[index+2],
            result: ['me'],
            explanation: '父亲的儿子是自己或兄弟'
        },
        {
            pattern: ['mother', 'son'],
            condition: (path, index) => index+1 < path.length && !path[index+2],
            result: ['me'],
            explanation: '母亲的儿子是自己或兄弟'
        },
        {
            pattern: ['father', 'daughter'],
            condition: (path, index) => index+1 < path.length && !path[index+2],
            result: ['me'],
            explanation: '父亲的女儿是自己或姐妹'
        },
        {
            pattern: ['mother', 'daughter'],
            condition: (path, index) => index+1 < path.length && !path[index+2],
            result: ['me'],
            explanation: '母亲的女儿是自己或姐妹'
        },
        
        // 父母关系简化
        {
            pattern: ['son', 'father'],
            result: ['me'],
            explanation: '儿子的父亲是自己(男性)'
        },
        {
            pattern: ['daughter', 'father'],
            result: ['me'],
            explanation: '女儿的父亲是自己(男性)'
        },
        {
            pattern: ['son', 'mother'],
            result: ['wife'],
            explanation: '儿子的母亲是自己的妻子'
        },
        {
            pattern: ['daughter', 'mother'],
            result: ['wife'],
            explanation: '女儿的母亲是自己的妻子'
        },

        // 同辈关系简化
        {
            pattern: ['father', 'son', 'elder_brother'],
            result: ['elder_brother'],
            explanation: '父亲的儿子的哥哥是自己的哥哥'
        },
        {
            pattern: ['father', 'son', 'younger_brother'],
            result: ['younger_brother'],
            explanation: '父亲的儿子的弟弟是自己的弟弟'
        },
        {
            pattern: ['father', 'son', 'elder_sister'],
            result: ['elder_sister'],
            explanation: '父亲的儿子的姐姐是自己的姐姐'
        },
        {
            pattern: ['father', 'son', 'younger_sister'],
            result: ['younger_sister'],
            explanation: '父亲的儿子的妹妹是自己的妹妹'
        },
        
        // 父母兄弟姐妹的子女
        {
            pattern: ['father', 'elder_brother', 'son'],
            result: ['father', 'elder_brother', 'son'],
            explanation: '父亲的哥哥的儿子是堂兄弟'
        }
    ];

    // 常见称呼列表
    const commonRelations = [
        { path: ['father', 'father'], text: '爷爷' },
        { path: ['father', 'mother'], text: '奶奶' },
        { path: ['mother', 'father'], text: '外公' },
        { path: ['mother', 'mother'], text: '外婆' },
        { path: ['father', 'elder_brother'], text: '伯父' },
        { path: ['father', 'younger_brother'], text: '叔叔' },
        { path: ['mother', 'elder_brother'], text: '舅舅' },
        { path: ['father', 'elder_sister'], text: '姑姑' },
        { path: ['mother', 'elder_sister'], text: '姨妈' },
        { path: ['son', 'son'], text: '孙子' },
        { path: ['son', 'daughter'], text: '孙女' },
        { path: ['daughter', 'son'], text: '外孙' },
        { path: ['daughter', 'daughter'], text: '外孙女' }
    ];

    /**
     * 应用关系简化规则
     * @param {Array} relationPath - 关系路径数组
     * @returns {Array} 简化后的路径
     */
    function applySimplificationRules(relationPath) {
        if (!relationPath || relationPath.length < 2) {
            return relationPath;
        }
        
        let simplified = [...relationPath];
        let hasChanges = true;
        
        // 反复应用规则直到无法进一步简化
        while (hasChanges) {
            hasChanges = false;
            
            for (let i = 0; i < simplified.length - 1; i++) {
                for (const rule of simplificationRules) {
                    // 检查是否匹配规则模式
                    let matches = true;
                    for (let j = 0; j < rule.pattern.length; j++) {
                        if (i + j >= simplified.length || simplified[i + j] !== rule.pattern[j]) {
                            matches = false;
                            break;
                        }
                    }
                    
                    // 如果存在条件函数，需要额外检查
                    if (matches && rule.condition && !rule.condition(simplified, i)) {
                        matches = false;
                    }
                    
                    // 应用规则
                    if (matches) {
                        const before = simplified.slice(0, i);
                        const after = simplified.slice(i + rule.pattern.length);
                        simplified = [...before, ...rule.result, ...after];
                        hasChanges = true;
                        break;
                    }
                }
                
                if (hasChanges) break;
            }
        }
        
        return simplified;
    }

    /**
     * 分析关系类型
     * @param {Array} relationPath - 关系路径数组
     * @returns {String} 关系类型
     */
    function analyzeRelationType(relationPath) {
        // 关系类型包括：自己、直系亲属、旁系亲属、姻亲等
        if (!relationPath || relationPath.length === 0) {
            return '自己';
        }
        
        // 检查是否为直系亲属（父母、子女、祖父母、孙子女）
        const directRelations = ['father', 'mother', 'son', 'daughter'];
        const isDirect = relationPath.every(rel => directRelations.includes(rel));
        
        if (isDirect) {
            return '直系亲属';
        }
        
        // 检查是否包含姻亲关系（丈夫、妻子）
        if (relationPath.some(rel => ['husband', 'wife'].includes(rel))) {
            return '姻亲';
        }
        
        // 其他情况为旁系亲属
        return '旁系亲属';
    }

    /**
     * 计算亲戚关系
     * @param {Array} relationPath - 关系路径数组
     * @returns {Object} 计算结果
     */
    function calculateRelation(relationPath) {
        if (!relationPath || relationPath.length === 0) {
            return { 
                text: '我', 
                call: '我',
                path: [],
                explanation: '这是你自己'
            };
        }

        // 尝试简化关系链
        const simplifiedPath = applySimplificationRules(relationPath);
        
        // 如果简化后的路径和原始路径不同，先尝试用简化后的路径计算
        let result = null;
        if (JSON.stringify(simplifiedPath) !== JSON.stringify(relationPath)) {
            result = calculateRelation(simplifiedPath);
            result.originalPath = relationPath;
            result.simplifiedPath = simplifiedPath;
            result.explanation = `关系被简化为: ${simplifiedPath.map(key => relations[key].text).join('的')}`;
            return result;
        }
        
        // 构建路径字符串用于查找复杂关系
        const pathString = relationPath.join(',');
        
        // 检查是否有预定义的复杂关系
        if (complexRelations[pathString]) {
            return {
                text: complexRelations[pathString].text,
                call: complexRelations[pathString].call,
                path: relationPath,
                explanation: `这是预定义的复杂关系: ${complexRelations[pathString].call}`
            };
        }
        
        // 如果没有预定义关系，尝试构建描述
        let description = '我';
        for (const relation of relationPath) {
            if (relations[relation]) {
                description += '的' + relations[relation].text;
            } else {
                description += '的未知关系';
            }
        }
        
        // 分析关系类型
        const relationType = analyzeRelationType(relationPath);
        
        return {
            text: description,
            call: description,
            path: relationPath,
            relationType: relationType,
            explanation: `这是${relationType}关系，无法进一步简化`
        };
    }

    /**
     * 获取关系描述
     * @param {String} relationKey - 关系键名
     * @returns {String} 关系描述
     */
    function getRelationText(relationKey) {
        return relations[relationKey] ? relations[relationKey].text : '未知关系';
    }

    /**
     * 获取常见关系列表
     * @returns {Array} 常见关系列表
     */
    function getCommonRelations() {
        return commonRelations;
    }

    // 公开API
    return {
        calculateRelation,
        getRelationText,
        getCommonRelations,
        applySimplificationRules
    };
})();

// 导出模块（如果在模块环境中）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = RelationEngine;
} 